package com.alexgaoyh.MutiModule.Dubbo.RWSeperate.consumer.web.manager.data.authority.group;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributesModelMap;

import com.MutiModule.common.myPage.MyPageView;
import com.MutiModule.common.mybatis.annotation.MyBatisTableAnnotation;
import com.MutiModule.common.twitter.IDGenerator.instance.IdWorkerInstance;
import com.MutiModule.common.utils.DateUtils;
import com.MutiModule.common.utils.StringUtilss;
import com.MutiModule.common.vo.enums.DeleteFlagEnum;
import com.MutiModule.common.vo.mybatis.pagination.Page;
import com.alexgaoyh.MutiModule.Dubbo.RWSeperate.api.manager.data.authority.group.read.ISqlDataAuthorityOperationGroupReadService;
import com.alexgaoyh.MutiModule.Dubbo.RWSeperate.api.manager.data.authority.group.write.ISqlDataAuthorityOperationGroupWriteService;
import com.alexgaoyh.MutiModule.Dubbo.RWSeperate.api.manager.data.authority.rule.read.ISqlDataAuthorityOperationRuleReadService;
import com.alexgaoyh.MutiModule.Dubbo.RWSeperate.consumer.web.base.BaseController;
import com.alexgaoyh.MutiModule.Dubbo.RWSeperate.persist.manager.data.authority.group.SqlDataAuthorityOperationGroup;
import com.alexgaoyh.MutiModule.Dubbo.RWSeperate.persist.manager.data.authority.view.SqlDataAuthorityOperationGroupWithRuleView;
import com.alexgaoyh.MutiModule.Dubbo.RWSeperate.persist.manager.data.authority.view.SqlDataAuthorityOperationView;
import com.alibaba.dubbo.config.annotation.Reference;

/**
*
* dubbo 消费者
 * SqlDataAuthorityOperationGroup 模块 读接口
 * @author alexgaoyh
*
*/
@Controller
@RequestMapping(value="manager/data/authority/group")
public class SqlDataAuthorityOperationGroupController extends BaseController<SqlDataAuthorityOperationGroup>{

	@Reference(group="readService", interfaceName="com.alexgaoyh.MutiModule.Dubbo.RWSeperate.api.manager.data.authority.group.read.ISqlDataAuthorityOperationGroupReadService")
	private ISqlDataAuthorityOperationGroupReadService readService;
	
	@Reference(group="writeService", interfaceName="com.alexgaoyh.MutiModule.Dubbo.RWSeperate.api.manager.data.authority.group.write.ISqlDataAuthorityOperationGroupWriteService")
	private ISqlDataAuthorityOperationGroupWriteService writeService;
	
	@Reference(group = "readService", interfaceName = "com.alexgaoyh.MutiModule.Dubbo.RWSeperate.api.manager.data.authority.rule.read.ISqlDataAuthorityOperationRuleReadService")
	private ISqlDataAuthorityOperationRuleReadService ruleReadService;
	
	@Override
	public ModelAndView list(ModelAndView model, HttpServletRequest request) {

		super.list(model, request);
		
		MyPageView<SqlDataAuthorityOperationGroup> pageView = decorateCondition(request);

		model.addObject("pageView", pageView);

		return model;

	}
	
	/**
	 * 封装参数部分
	 * @param request
	 * @return
	 */
	protected MyPageView<SqlDataAuthorityOperationGroup> decorateCondition(HttpServletRequest request) {
		
		String currentPageStr = request.getParameter("currentPage");
		if(StringUtilss.isEmpty(currentPageStr)) {
			currentPageStr = "1";
		}
		
		String recordPerPageStr = request.getParameter("recordPerPage");
		if(StringUtilss.isEmpty(recordPerPageStr)) {
			recordPerPageStr = "10";
		}

		int beginInt = Integer.parseInt(currentPageStr) >=1 ? Integer.parseInt(currentPageStr) : 1;
		
		Page page = new Page((beginInt - 1)*Integer.parseInt(recordPerPageStr), Integer.parseInt(recordPerPageStr));
		
		Map<Object, Object> map = new HashMap<Object, Object>();
		map.put("page", page);
		
		//TODO 搜索条件添加
		
		MyPageView<SqlDataAuthorityOperationGroup> pageView = readService.generateMyPageViewVO(map);
		
		return pageView;
	}
	
	@Override
	public ModelAndView add(ModelAndView model, HttpServletRequest request) {
		
		Map<String, List<SqlDataAuthorityOperationView>> operationViewMapWithClassPath = generateOperationViewMapWithClassPath();
		
		model.addObject("operationViewMapWithClassPath", operationViewMapWithClassPath);
		
		super.add(model, request);
		return model;
		
	}
	
	@RequestMapping(value="/doSaveView")
	public ModelAndView doSaveView(@RequestParam(value = "ruleId") String ruleIdStrs, ModelAndView model, HttpServletRequest request, SqlDataAuthorityOperationGroup entity, RedirectAttributesModelMap modelMap) throws Exception  {
		model.setViewName("redirect:list");
		
		String nameStr = request.getParameter("name");
		String remarksStr = request.getParameter("remarks");
		if(StringUtilss.isNotEmpty(nameStr) && StringUtilss.isNotEmpty(remarksStr)) {
			SqlDataAuthorityOperationGroup group = new SqlDataAuthorityOperationGroup();
			group.setId(IdWorkerInstance.getIdStr());
			group.setDeleteFlag(DeleteFlagEnum.NORMAL);
			group.setCreateTime(DateUtils.getGMTBasicTime());
			group.setName(nameStr);
			group.setRemarks(remarksStr);
			writeService.insertOperationGroupWithRuleView(group, ruleIdStrs.split(","));
		} else {
			// throw exception
		}
		
		return model;
	}
	
	@RequestMapping(value="/show/{id}")
	public ModelAndView show(@PathVariable("id") String id, ModelAndView model, HttpServletRequest request, RedirectAttributesModelMap modelMap) throws Exception  {
		super.show(id, model, request, modelMap);
		
		SqlDataAuthorityOperationGroupWithRuleView operationView = readService.selectGroupWithRuleByPrimaryKey(id);
		model.addObject("entity", operationView);
		
		Map<String, List<SqlDataAuthorityOperationView>> operationViewMapWithClassPath = generateOperationViewMapWithClassPath();
		model.addObject("operationViewMapWithClassPath", operationViewMapWithClassPath);
		
		return model;
	}
	
	/**
	 * 返回map集合， key 	为 MyBatisTableAnnotation.remarks();
	 * 			 value  为 数据库中配置的所有此 key 下的 数据权限规则
	 * @return
	 */
	private Map<String, List<SqlDataAuthorityOperationView>> generateOperationViewMapWithClassPath() {
		Map<String, List<SqlDataAuthorityOperationView>> operationViewMapWithClassPath = new HashMap<String, List<SqlDataAuthorityOperationView>>(); 
		try {
			
			Map<Object, Object> map = new HashMap<Object, Object>();
			map.put("deleteFlag", DeleteFlagEnum.NORMAL);
			List<SqlDataAuthorityOperationView> operationViewList = ruleReadService.selectListWithOperationModelByMap(map);
			if(operationViewList != null && operationViewList.size() > 0) {
				for (SqlDataAuthorityOperationView sqlDataAuthorityOperationView : operationViewList) {
					String classPath = sqlDataAuthorityOperationView.getClassPath();
					if(StringUtilss.isNotEmpty(classPath)) {
						Class<?> _clazz = Class.forName(classPath);
						MyBatisTableAnnotation tableAnnotation = _clazz.getAnnotation(MyBatisTableAnnotation.class);
						if(tableAnnotation != null) {
							String _tableNameRemarks = tableAnnotation.remarks();
							List<SqlDataAuthorityOperationView> _view = operationViewMapWithClassPath.get(_tableNameRemarks);
							if(_view != null && _view.size() > 0) {
								_view.add(sqlDataAuthorityOperationView);
							} else {
								_view = new ArrayList<SqlDataAuthorityOperationView>();
								_view.add(sqlDataAuthorityOperationView);
							}
							operationViewMapWithClassPath.put(_tableNameRemarks, _view);
						}
					}
				}
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return operationViewMapWithClassPath;
	}

}
